package com.guiji.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.guiji.constant.Constant;
import com.guiji.convert.CaseInfoConvert;
import org.apache.commons.collections.MapUtils;
import org.apache.poi.ss.usermodel.*;

import java.io.*;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xue
 * @ClassName: ExcelUtils
 * @Date: Created in 1:22 2021/10/29
 * @Description:
 */
public class ExcelUtils {
    public static void main(String[] args) {
        List<Map<String, Object>> maps = readExcel(Constant.TEST_CASE_PATH, 3);
        maps.forEach(m -> m.forEach((k, v) -> System.out.println(k + "--->" + v)));
//        List<String> allBusinessName = getAllBusinessName(Constant.TEST_CASE_PATH);
//        allBusinessName.forEach(System.out::println);
    }

    public static List<String> getAllSheetName(String path) {
        List<String> businessNames = new ArrayList<>();
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(new FileInputStream(path));
            for (int i = 1; i < workbook.getNumberOfSheets(); i++) {
                businessNames.add(workbook.getSheetName(i));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(workbook);
        }
        return businessNames;
    }

    public static List<Map<String, Object>> readExcel(String path, int sheetNum) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(new FileInputStream(path));
            Sheet sheet = workbook.getSheetAt(sheetNum);
            Row headRow = sheet.getRow(0);
            List<String> headers = new ArrayList<>();
            if (headRow == null) {
                return mapList;
            }

            for (int i = 0; i < headRow.getLastCellNum(); i++) {
                Cell cell = headRow.getCell(i);
                headers.add(String.valueOf(getValue(cell)));
            }

            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row currentRow = sheet.getRow(i);
                if (currentRow != null) {
                    Map<String, Object> map = new LinkedHashMap<>();
                    for (int j = 0; j < currentRow.getLastCellNum(); j++) {
                        map.put(headers.get(j), getValue(currentRow.getCell(j)));
                    }
                    if (MapUtils.isNotEmpty(map)) {
                        mapList.add(map);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(workbook);
        }

        return mapList;
    }

    public static void close(Closeable closeable) {
        try {
            if (closeable != null)
                closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Object getValue(Cell cell) {
        NumberFormat numberFormat = NumberFormat.getInstance();
        numberFormat.setGroupingUsed(false);
        if (cell.getCellType() == CellType.BOOLEAN) {
            return cell.getBooleanCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            // poi导入自动添加小数点处理
            return numberFormat.format(cell.getNumericCellValue());
        } else {
            return cell.getStringCellValue();
        }
    }


    public static <T> List<T> readAllData(String filePath, int sheetNum, Class<T> clazz) {
        return read(filePath, sheetNum, 1, 0, clazz);
    }

    public static <T> List<T> readSpecialData(String filePath, int sheetNum, int startRow, Class<T> clazz) {
        return read(filePath, sheetNum, startRow, 0, clazz);
    }

    public static <T> T readOneData(String filePath, int sheetNum, int startRow, Class<T> clazz) {
        return read(filePath, sheetNum, startRow, 1, clazz).get(0);
    }


    public static <T> List<T> readSpecialRowData(String filePath, int sheetNum, int startRow, int readRows, Class<T> clazz) {
        return read(filePath, sheetNum, startRow, readRows, clazz);

    }

    public static <T> List<T> read(String filePath, int sheetNum, int startRow, int readRow, Class<T> clazz) {
        File file = new File(filePath);
        ImportParams importParams = new ImportParams();
        importParams.setStartSheetIndex(sheetNum - 1);
        importParams.setStartRows(startRow - 1);
        importParams.setReadRows(readRow);
        CaseInfoConvert convert = new CaseInfoConvert();
        convert.setNeedHandlerFields(new String[]{"params"});
        importParams.setDataHandler(convert);
        return ExcelImportUtil.importExcel(file, clazz, importParams);
    }

    public static void writerListToExcel(List<?> list, String sheetName, String outputFilePath, Class<?> clazz) {
        Workbook workbook = null;
        FileOutputStream fos = null;
        try {
            ExportParams exportParams = new ExportParams();
            exportParams.setType(ExcelType.XSSF);
            exportParams.setSheetName(sheetName);
            workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
            fos = new FileOutputStream(outputFilePath);
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert fos != null;
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
